<?php

namespace xiaoshao\weixin;

class Wxofficial
{
    private $scope = [
        1 => 'snsapi_userinfo',
        2 => 'snsapi_base',
    ];
    /**
     * 公众号登陆获取登陆地址
     * @param $url                  此地址是前端的一个地址，此页面地址必须能够获得微信回调回来的参数并请求user.officiallogin接口
     * @param string $scope         应用授权作用域，snsapi_userinfo或者snsapi_base
     * @return array
     */
    public function geturl($url,$appid,$secret,$scope=1){
        
        $url = urlencode($url);
        return  "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$appid."&redirect_uri=".$url."&response_type=code&scope=".$this->scope[$scope]."&state=1#wechat_redirect";
    }
    
    public function codeToInfo($code,$appid,$secret){

        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$appid."&secret=".$secret."&code=".$code."&grant_type=authorization_code";
        
        $re = $this->get($url);
        
        $data = json_decode($re,true);
        
        if(isset($data['errcode'])){
            $result['msg'] = $data['errmsg'];
            return $result;
        }
        
        //根据access_token拉取用户信息
        $url = "https://api.weixin.qq.com/sns/userinfo?access_token=".$data['access_token']."&openid=".$data['openid']."&lang=zh_CN";

        $re = $this->get($url);
        $data = json_decode($re,true);
        
        if(isset($data['errcode'])){
            return $data;
        }
        //到这里就取到用户的信息了
        return $data;
    }
    private function get($url)
    {
        $oCurl = curl_init();
        if (stripos($url, "https://") !== FALSE) {
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);
            curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
        }
        if (defined('CURLOPT_IPRESOLVE') && defined('CURL_IPRESOLVE_V4')) {
            curl_setopt($oCurl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
        }
        curl_setopt($oCurl, CURLOPT_URL, $url);
        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);
        $sContent = curl_exec($oCurl);
        $aStatus  = curl_getinfo($oCurl);
        curl_close($oCurl);
        if (intval($aStatus["http_code"]) == 200) {
            return $sContent;
        } else {
            return false;
        }
    }
}
